/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.testis.gui.mvc.view.labels;

import org.testis.orm.labelhandler.ILabelTreeBuilder;
import org.testis.orm.labelhandler.LabelRefined;
import org.testis.orm.labelhandler.TristateLabelTreeBuilder;
import org.testis.utils.tree.DefaultMutableLabelNode;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.testis.utils.tree.LabelTreeNode;
import org.testis.utils.tree.TreeNode;

/**
 *
 * @author selcuk
 */
public class TristateLabelTreeLoader implements ILabelTreeLoader {

    @Override
    public DefaultMutableLabelNode loadTree() {
        DefaultMutableLabelNode rootNode = loadPrivate(null);
        return rootNode;
    }

    @Override
    public DefaultMutableLabelNode loadTree(List<Integer> selectedLabels) {
        DefaultMutableLabelNode rootNode = loadPrivate(selectedLabels);
        return rootNode;
    }

    private DefaultMutableLabelNode loadPrivate(List<Integer> selectedLabels) {
        ILabelTreeBuilder builder = new TristateLabelTreeBuilder();
        LabelTreeNode rootNode = builder.buildLabelTree();
        return loadRecursive(rootNode, selectedLabels);
    }

    private DefaultMutableLabelNode loadRecursive(LabelTreeNode obj, List<Integer> selectedLabels) {
        if (obj == null) {
            return null;
        }
        LabelRefined refined = (LabelRefined) obj.getObject();
        if (refined != null && selectedLabels != null
                && selectedLabels.contains(refined.getId())) {
            obj.setSelected(true);
        }
        DefaultMutableLabelNode result = new DefaultMutableLabelNode(obj);
        LinkedList<TreeNode> children = obj.getChildrenLinkedList();
        for (Iterator<TreeNode> it = children.iterator(); it.hasNext();) {
            LabelTreeNode child = (LabelTreeNode) it.next();
            DefaultMutableLabelNode childNode = loadRecursive(child,
                    selectedLabels);
            result.add(childNode);
        }
        return result;
    }
}
